package com.wiloon.java.network.network.nettyhttpserver.nettyhttpclient;

/**
 * Created by Roy on 2015/12/17;
 */




import com.wiloon.java.network.network.nettyhttpserver.monitor.ResponseCounter;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@ChannelHandler.Sharable
public class HttpClientHandler extends ChannelHandlerAdapter {
    private final static Logger logger = LoggerFactory.getLogger(HttpClientHandler.class);
    boolean closeConnection = false;

    public HttpClientHandler(boolean closeConnection) {
        this.closeConnection = closeConnection;
    }


    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        try {
            if (msg instanceof HttpResponse) {
                HttpResponse response = (HttpResponse) msg;
                ResponseCounter.count();
            }
            if (msg instanceof HttpContent) {
                HttpContent content = (HttpContent) msg;
                ByteBuf buf = content.content();

                //  logger.info(buf.toString(io.netty.util.CharsetUtil.UTF_8));
                // logger.trace("receive channel:{}", ctx.channel());

                if (closeConnection) ctx.close();
                buf.release();
            }
        } catch (Exception e) {
            logger.error("failed  handler.");
            e.printStackTrace();
        }
    }


    public void channelInactive(ChannelHandlerContext ctx) throws Exception {

        ctx.close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        logger.error("failed :{}", cause.getMessage());
        cause.printStackTrace();
        ctx.close();
    }
}